import React, { Component } from 'react';
import { Checkbox, Button } from 'antd';
import PropTypes from 'prop-types';

import './virtualScroll.scoped.less';

export default class VirtualScroll extends Component {
  static propTypes = {
    itemHeight: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.number.isRequired]), // 每一项的高度
  };
  static defaultProps = {
    list: [],
    onMouseLeave: () => {},
  };

  state = {
    top: 0,
    wrapHeight: 0, // 容器的高度
    height: this.props.itemHeight ? this.props.list.length * this.props.itemHeight : 'auto',
  };

  scrollWrap = React.createRef(); // 滚动的盒子

  componentDidMount = () => {
    this.scrollWrap.current.onscroll = () => {
      // 设置显示内容定位高度
      let { scrollTop, scrollLeft, clientHeight, scrollHeight } = this.scrollWrap.current;
      const point = scrollTop % this.props.itemHeight;
      // console.log(point, scrollTop);
      const top = scrollTop - point;
      this.setState({ top });

      if (typeof this.props.onScroll === 'function') {
        this.props.onScroll({ scrollTop, top, scrollLeft, clientHeight, scrollHeight });
      }
    };
  };

  render() {
    // console.log(this.state.top);
    const tableData = this.props.list;

    let end = 0;
    let data = tableData.slice(0, end);

    if (this.scrollWrap.current) {
      const { scrollTop, clientHeight } = this.scrollWrap.current;
      // this.state.top = scrollTop + 'px';
      const start = Math.floor(+scrollTop / this.props.itemHeight);
      // console.log(start);
      end = Math.ceil(clientHeight / this.props.itemHeight) + 2;
      data = tableData.slice(start, start + end);
    }

    // 如果是拉到最底部
    const positionStyle = {
      top: this.state.top + 'px',
    };
    if (data.length < end - 1) {
      positionStyle.top = 'initial';
      positionStyle.bottom = '0px';
    }
    // console.log(positionStyle.top);

    let children = null;
    if (typeof this.props.children === 'function') {
      children = this.props.children({ ...this.props, list: data, isLast: data.length < end - 1 });
    }

    return (
      <div
        onMouseLeave={this.props.onMouseLeave}
        ref={this.scrollWrap}
        style={{
          position: 'relative',
          height: '500px',
          overflow: 'auto',
          width: '100%',
        }}
      >
        <div
          style={{
            height: this.state.height,
            position: 'relative',
            width: '100%',
          }}
        >
          <div style={{ width: '100%', position: 'absolute', ...positionStyle }}>{children}</div>
        </div>
      </div>
    );
  }
}
